import { Component, OnInit, ViewChild, OnChanges, Input, ElementRef } from '@angular/core';
import { ModelListService } from '../../../services/project/model/model-list.service';
import { listModel, addModel, imgType, modelType } from './model-list.model';
import { ZzjFileUploader, FlowFileModel } from '@zzj/nag-file-uploader';
import { FILEURL } from './../../../config';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { Status, Utils, Task } from '../../../common/helper/util-helper';
import { FileUploaderComponent } from '../../../components/file-uploader/file-uploader.component';
import { hash } from 'spark-md5';
import { Subject } from 'rxjs';
import { async } from 'q';

@Component({
  selector: 'app-model-list',
  templateUrl: './model-list.component.html',
  styleUrls: ['./model-list.component.scss']
})
export class ModelListComponent implements OnInit {

  @ViewChild('imageUploader', { static: false }) imageUploader: FileUploaderComponent;
  @ViewChild('modelUploader', { static: false }) modelUploader: FileUploaderComponent;
  @ViewChild('uploadModel', { static: false }) uploadModel: ElementRef; // 找到第一个符合条件的节点执行替换重新上传
  @Input() id: any;

  constructor(
    private modelListService: ModelListService,
    private router: Router,
    private routeInfo: ActivatedRoute,
    private modalService: NzModalService,
    private message: NzMessageService
  ) {
  }
  public survey = `/inner/project/${JSON.parse(window.localStorage.getItem('project')).id}/survey?info=project`;
  // tslint:disable-next-line: max-line-length
  public createUserId = JSON.parse(window.localStorage.getItem('project')) ? JSON.parse(window.localStorage.getItem('project')).creatorUserId : '';
  public userId = JSON.parse(window.localStorage.getItem('APDInfo')).userId;
  public project = JSON.parse(window.localStorage.getItem('project'))
  // 模型列表
  public modelLists: any = [];

  // 模型组列表
  public modelGroupLists: any = [];
  public findJson = new listModel();
  public nzTotal: number = 0;
  public nzPageIndex: number = 1;
  public isAddVisible: boolean = false;
  public imgQueue: any = [];
  public modelQueue: any = [];
  public FILEURL = FILEURL;
  public addModelInfo = new addModel();
  public delFileId:any='';
  public imgStyle: any = {};
  public imgShow: boolean = true;
  public modelStyle: any = { 'display': 'none' };
  public modelShow: boolean = true;
  public groupJwStatus: any = 0; //场景推送状态（1=审核中；2=已通过；3=不通过）
  public anaJson: any;
  public projectName: string = JSON.parse(window.localStorage.getItem('project')).name;
  public addLoading: boolean = false;
  public editModelInfo = new addModel();
  public isEditVisible: boolean = false;
  public imgType: any = imgType;
  public modelType: any = modelType;
  public imgUpLists: any = [];
  // 新建模型组
  public isAddGroupVisible = false;
  // 编辑模型组
  public isEditGroupVisible = false;
  // 编辑该模型组模型
  public isShowGroupModelList = false;
  // 模型组名称
  public GroupModelName: string;
  public GroupModelTitle: string;
  // 前端生成的modelGroupId
  public modelGroupId = null;
  // 上传模型的文件名
  public fileName = '';
  // 上传模型的hash值
  public fileHash = '';
  // SSOCreatorUserId
  public SSOCreatorUserId: '';
  // 待解析模型数组
  public anaJsonArr = [];
  // 是否显示模型的删除按钮
  public isDel = true;
  // 提交审核弹出框
  public subAuditVisible = false;
  // 当前操作的模型组
  public currentModelGroup: any;
  // 审核结果列表
  public modelResLists = [];
  // 审核结果弹窗
  public isShowModelResList = false;
  // 控制审核信息是，输入框可选
  public isConvert = true;
  // 根据状态判断是否显示上传
  public isaudit = true;
  // 是否显示审核
  public isbtn = false;
  // 是否显示审核状态字段,评审结果按钮
  public isauditstatus = false;
  // 文件上传状态监听
  public fileLoadStatus: Subject<any> = new Subject;
  // 标记上传模型执行状态
  public handleAddOkStatus = false;
  public status = {
    // 当前页面所需要的企业权限
    pagePermissions: [],
    // 所需项目级权限
    PIpagePermissions: [
      // 模型管理
      'APJ.PI.Models',
    ],
    // 当前页面企业级权限状态
    // tslint:disable-next-line: max-line-length
    pageAuthorty: {},
    // 当前页面项目级权限状态
    PIpageAuthorty: {
      PIModels: null,
    },


    // 建委审核
    pro: {
      // 项目信息
      code: '',
      name: '',
      // tslint:disable-next-line: max-line-length
      aeraArr: [{ label: '万州区', value: 110 }, { label: '涪陵区', value: 109 }, { label: '渝中区', value: 101 }, { label: '大渡口区', value: 107 }, { label: '江北区', value: 102 }, { label: '沙坪坝区', value: 106 }, { label: '九龙坡区', value: 105 }, { label: '南岸区', value: 103 }, { label: '北碚区', value: 108 }, { label: '綦江区', value: 122 }, { label: '大足区', value: 123 }, { label: '渝北区', value: 124 }, { label: '巴南区', value: 125 }, { label: '黔江区', value: 126 }, { label: '长寿区', value: 127 }, { label: '江津区', value: 128 }, { label: '合川区', value: 129 }, { label: '永川区', value: 130 }, { label: '南川区', value: 131 }, { label: '璧山区', value: 132 }, { label: '铜梁区', value: 133 }, { label: '潼南区', value: 134 }, { label: '荣昌区', value: 135 }, { label: '开州区', value: 136 }, { label: '梁平区', value: 137 }, { label: '武隆区', value: 138 }, { label: '城口县', value: 139 }, { label: '丰都县', value: 140 }, { label: '垫江县', value: 141 }, { label: '忠县', value: 142 }, { label: '云阳县', value: 143 }, { label: '奉节县', value: 144 }, { label: '巫溪县', value: 145 }, { label: '石柱土家族自治县', value: 146 }, { label: '秀山土家族苗族自治县', value: 147 }, { label: '酉阳土家族苗族自治县', value: 148 }, { label: '彭水苗族土家族自治县', value: 149 }],
      aera: { label: '渝中区', value: 101 },
      typeArr: [
        { label: '市政公用', value: '市政公用' },
        { label: '房屋建筑', value: '房屋建筑' },
      ],
      type: { label: '市政公用', value: '市政公用' },
      stepArr: [
        { label: '初步设计阶段', value: 'PRELIMINARY_DESIGN_PHASE' },
        { label: '施工图设计阶段', value: 'CONSTRUCTION_DESIGN_PHASE' },
        { label: '施工应用阶段', value: 'CONSTRUCTION_APPLY_PHASE' },
        { label: '竣工阶段', value: 'COMPLETION_PHASE' },
        { label: '档案阶段', value: 'ARCHIVAL_PHASE' },
      ],
      step: { label: '施工应用阶段', value: 'CONSTRUCTION_APPLY_PHASE' },
      progressArr: [
        { label: '基础', value: 'BASE' },
        { label: '主体结构', value: 'MAIN_STRUCTURE' },
        { label: '装饰装修', value: 'DECORATION' }
      ],
      progress: { label: '主体结构', value: 'MAIN_STRUCTURE' },
      info: '',
      // 模型信息
      modelName: '',
      fileTypeArr: [
        { label: '模型文件', value: '模型文件' },
        { label: '普通文件', value: '普通文件' },
      ],
      fileType: { label: '模型文件', value: '模型文件' },
      modelTypeArr: [
        { label: '基础模型', value: 'BASE_MODEL' },
        { label: '整体模型', value: 'INTEGRAL_MODEL' },
        { label: '局部应用模型', value: 'PARTIAL_MODEL' },
      ],
      modelType: { label: '整体模型', value: 'INTEGRAL_MODEL' },
      modelprogress: { label: '基础模型', value: 'BASE_MODEL' },
      modelprogressArr: [
        { label: '基础模型', value: 'BASE_MODEL' },
        { label: '进度模型', value: 'RATE_MODEL' },
      ]
    },

  }
  // 绑定 输入框
  compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.value === o2.value : o1 === o2);
  /**
   * 初始化
   */
  public async init() {
    // 匹配权限
    if (JSON.parse(window.localStorage.getItem('APDInfo'))['roleCode'] !== 'Admin' && this.userId !== this.createUserId) {
      this.status.PIpageAuthorty = Utils.PIgrantedPermissions(
        this.status.PIpagePermissions,
        this.status.PIpageAuthorty,
        true
      )
    } else {
      // tslint:disable-next-line: forin
      for (let key in this.status.PIpageAuthorty) {
        // console.log(key)
        this.status.PIpageAuthorty[key] = true;
      }
    }
    // console.log(this.status.PIpageAuthorty)
    // 获取模型组列表
    this.findJson.projectId = JSON.parse(window.localStorage.getItem('project')).id;
    const result = await this.modelListService.QueryModelGroupsPagedList(this.findJson);
    this.modelGroupLists = result.result.items;
    this.nzTotal = result.result.totalCount;
    this.getImg(this.modelGroupLists)
  }

  routeToSurvey() {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.router.navigate([`/inner/project/${projectId}/survey`], { queryParams: { info: 'project' } });
  }

  public async pageChange(index) {
    this.findJson.skipCount = index - 1;
    this.init();
  }

  public getImg(data) {
    data.forEach(el => {
      if (el.imageUrl) {
        el.img = { 'background-image': 'url(' + el.imageUrl + ')' };
      }
    });
  }

  public async search() {
    this.findJson.skipCount = 0;
    await this.init();
  }


  /**
    * 前端生成Guid
    * @private
    * @returns
    */
  private getGuid() {
    let s = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    // tslint:disable-next-line: no-bitwise
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';
    let uuid = s.join('');
    return uuid;
  }
  // **************************** 场景相关 ******************************************************************
  // 显示当前场景模型列表
  async showModelList(item) {
    console.log(item)
    this.status.pro.code = this.project.code;
    this.status.pro.name = this.project.name;
    this.status.pro.modelName = item.name;
    this.status.pro.info = this.project.description;
    this.anaJsonArr = [];
    this.currentModelGroup = item;
    this.GroupModelTitle = item.name;
    this.isShowGroupModelList = true;


    // 保存当前的 modelGroupId
    this.modelGroupId = item.id;
    let pramas = {
      modelGroupId: item.id,
      maxResultCount: 1000,
      projectId: item.projectId
    }
    const res = await this.modelListService.getModelLists(pramas);
    if (res.success) {
      // console.log(res)
      this.modelLists = res.result.items;
    } else {
      this.message.warning(res.error.message);
    }
    // 审核中隐藏上传模型按钮
    if (item.jwStatus == 1) {
      this.isaudit = false;
    }
    // 是否显示审核按钮
    if (item.type == 1 && item.jwStatus == 0) {
      this.isbtn = true;
    } else {
      this.isbtn = false;
    }
    // 是否显示审核状态字段
    if (item.type == 1) {
      this.isauditstatus = true
    } else {
      this.isauditstatus = false
    }
    // 根据转换进度判断是否显示删除按钮

    if (item.taskId !== '00000000-0000-0000-0000-000000000000') {
      const json = {
        ModelGroupId: item.id,
        taskId: item.taskId
      }
      const result = await this.modelListService.transformation(json);
      console.log(result)
      if (!result.item.taskState.done) {
        this.isDel = false;
        // this.message.create('warning', '当前场景下模型转换未完成，不能进行删除模型操作');

      } else {
        this.isDel = true;
      }
      console.log(this.isDel)
    }

  }
  // 关闭模型列表页面
  handleGroupCancel() {
    this.isaudit = true;
    this.isShowGroupModelList = false;
    this.init()
  }


  /**
   * 删除当前场景下的模型
   * @param id
   * @param type 默认删除， type =1 替换
   * @param delStatus
   */
  public async deleteModel(item, type?, delStatus?: boolean) {
    // console.log(item)
    this.modalService.error({
      nzTitle: '确认要删除这个模型吗?',
      nzContent: '<b style="color: red;">删除后不能恢复，请谨慎操作。</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {
        //  业务端模型删除
        let delRes = await this.modelListService.deleteModel({ input: item.id });
        if (delRes.success) {

          // 重新请求数据列表
          let pramas = {
            modelGroupId: item.modelGroupId,
            maxResultCount: 1000,
            projectId: item.projectId
          }
          const res = await this.modelListService.getModelLists(pramas);
          if (res.success) {
            // console.log(res)
            this.modelLists = res.result.items;
          } else {
            this.message.warning(res.error.message);
          }
        } else {
          this.message.warning(delRes.error.message);
        }

        // 图形服务端删除模型
        let Params = {
          hash: item.hash,
          modelGroupId: item.modelGroupId,
          modelName: item.fileName
        }
        const serDelRes = await this.modelListService.delModelFromGraphicsServer(Params);
        if (serDelRes.success && delRes.success) {
          if (type !== 1) {
            this.message.success('删除成功')
          }
          delStatus = true;
        } else {
          this.message.warning(serDelRes.error.message || delRes.error.message);
          delStatus = false;
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }




  // 添加模型组
  public async addModelGroup() {
    this.isAddGroupVisible = true;
    this.modelGroupId = this.getGuid();
    // console.log(this.modelGroupId)
    this.imgShow = true;
    this.imgStyle = {};
  }
  // 确定添加模型组
  public async handleAddGroupOk() {
    if (!this.GroupModelName) {
      this.message.create('warning', '请输入场景名称');
      return;
    }
    let pramas = {
      id: this.modelGroupId,
      name: this.GroupModelName,
      projectId: JSON.parse(window.localStorage.getItem('project')).id,
      creatorUserName: JSON.parse(window.localStorage.getItem('APDInfo'))['userName'],
      imageUrl: this.addModelInfo.imageUrl
    }
    const res = await this.modelListService.CreatOrModifyModelGroup(pramas);
    if (res.success) {
      this.message.success('操作成功');
    } else {
      this.message.warning(res.error.message);
    }
    await this.init();
    this.isAddGroupVisible = false;
  }

  /**
   * 修改场景
   * @param item
   */
  public editModelGroup(item) {
    console.log(item)
    this.GroupModelTitle = item.name;
    this.isEditGroupVisible = true;
    this.GroupModelName = item.name;
    this.modelGroupId = item.id;
    this.addModelInfo.imageUrl = item.imageUrl;
    this.imgShow = false;
    if (item.imageUrl) {
      this.imgShow = false;
      this.imgStyle = {
        'background-image': 'url(' + item.imageUrl + ')'
      };
    } else {
      this.imgShow = true;
    }
  }
  // 确认修改场景
  public async handleEditGroupOk() {
    if (!this.GroupModelName) {
      this.message.create('warning', '请输入场景名称');
      return;
    }
    let pramas = {
      id: this.modelGroupId,
      name: this.GroupModelName,
      projectId: JSON.parse(window.localStorage.getItem('project')).id,
      creatorUserName: JSON.parse(window.localStorage.getItem('APDInfo'))['userName'],
      imageUrl: this.addModelInfo.imageUrl
    }
    this.isEditGroupVisible = false;
    await this.modelListService.CreatOrModifyModelGroup(pramas);
    this.init();
  }



  // 删除场景
  public async RemoveModelGroup(item) {
    console.log(item)
    this.modalService.error({
      nzTitle: '确认要删除此场景吗?',
      nzContent: '<b style="color: red;">该场景下的所有模型将被删除，删除后不能恢复，请谨慎操作。</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {
        //  业务端模型删除
        const delRes = await this.modelListService.RemoveModelGroup({ id: item.id });
        if (delRes.success) {
          this.message.success('删除成功')
          // 重新请求场景列表
          this.init()
        } else {
          this.message.warning(delRes.error.message);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }

  // 关闭添加编辑模型组模态框
  CancelGroup() {
    this.isAddGroupVisible = false;
    this.isEditGroupVisible = false;
  }


  // 封面图片
  public async fileImgChange(e) {
    this.imgUpLists.forEach(el => {
      if (e.target.files[0].name === el.name) {
        this.imgSuccess(el);
        return;
      }
    });
    this.imageUploader.add(e.target.files[0]);
  }

  public imgSuccess(transfer: FlowFileModel) {
    // console.log(transfer)
    this.imgUpLists.push(transfer);
    this.imgShow = false;
    this.imgStyle = {
      'background-image': 'url(' + transfer.url + ')'
    };
    this.addModelInfo.imageUrl = transfer.url;
  }

  // 模型上传（文件服务）
  public async fileModelChange(e) {
    this.modelStyle['display'] = 'block';
    this.modelShow = false;
    // 判断不能重复上传已存在模型
    let ext = this.modelLists.find((el) => {
      return el.fileName == e.target.files[0].name;
    })
    if (!ext) {
      this.modelUploader.add(e.target.files[0]);
    } else {
      this.reModel()
      this.message.warning('已存在该模型')

    }

  }
  // 模型文件上传文件服务器成功回调
  public async modelSuccess(transfer: FlowFileModel) {
    console.log(transfer)
    this.fileName = transfer.fileInfo.name;
    this.fileHash = transfer.fileInfo.hash;
    this.SSOCreatorUserId = transfer.fileInfo.createdUserId;
    this.addModelInfo.size = transfer.size;
    this.anaJson = {
      // 文件服务返回的ID
      // id: transfer.fileInfo.id,
      name: transfer.fileInfo.name,
      path: transfer.fileInfo.path,
      modelGroupId: this.modelGroupId,
      hash: transfer.fileInfo.hash,
      type: transfer.fileInfo.type,
      SSOCreatorUserId: this.SSOCreatorUserId
      // tags: transfer.fileInfo.tag  // 转换时不需要该字段
    }
    await this.handleAddOk()
    this.reModel()
  }


  public reModel() {
    this.modelShow = true;
    this.modelStyle['display'] = 'none';
  }


  // 文件上传成功后回调执行 保存模型文件数据到（业务端）
  public async handleAddOk() {
    if (this.modelShow) {
      this.message.create('warning', '请上传模型');
      return;
    }
    this.addLoading = true;
    this.addModelInfo.projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.addModelInfo.path = this.anaJson.path;
    this.addModelInfo.modelGroupId = this.modelGroupId;
    this.addModelInfo.creatorUserName = JSON.parse(window.localStorage.getItem('APDInfo'))['userName'];
    this.addModelInfo.fileName = this.fileName;
    this.addModelInfo.hash = this.fileHash;
    this.addModelInfo.SSOCreatorUserId = this.SSOCreatorUserId;
    this.addModelInfo.type = this.anaJson.type;
    console.log(this.addModelInfo)

    // 上传模型 业务端请求
    let uploadres = await this.modelListService.addModel(this.addModelInfo);
    this.addLoading = false;
    this.isAddVisible = false;
    if (uploadres.success) {
      this.delFileId = uploadres.result;
      // 标记上传模型文件状态
      this.handleAddOkStatus = true;
      this.fileLoadStatus.next(this.handleAddOkStatus);
      // 上传成功后请求列表
      let pramas = {
        modelGroupId: this.anaJson.modelGroupId,
        maxResultCount: 1000,
        projectId: this.addModelInfo.projectId
      }
      const res = await this.modelListService.getModelLists(pramas);
      if (res.success) {
        this.modelLists = res.result.items;
        

      } else {
        this.message.warning(res.error.message);
      }
    } else {
      this.handleAddOkStatus = false;
      this.message.warning(uploadres.error.message);
    }

  }

  // 文件上传完成后集中发起解析
  public async goanalysisModel(type) {
    if (this.modelLists.length === 0) { this.message.warning('请先上传模型'); return; }
    this.modalService.info({
      nzTitle: '确认保存?',
      nzContent: '<b style="color: red;">上传的模型文件将会被保存，并开始模型转换</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {
        const parmas = {
          modelGroupId: this.modelGroupId,
          projectId: JSON.parse(window.localStorage.getItem('project')).id,
        }
        const resultAna = await this.modelListService.ConvertModel(parmas);
        console.log(resultAna)
        if (resultAna.success) {
          this.message.success('保存成功');
        } else {
          this.message.error(Utils.errorMessageProcessor(resultAna) || '保存失败');
        }
        // 关闭关闭弹窗并刷新模型组列表
        this.handleGroupCancel();

      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });




  }

  // 关闭上传弹窗
  public handleCancel() {
    this.isAddVisible = false;
    this.isEditVisible = false;

  }

  // 提交建委审核
  public subAudit() {
    this.subAuditVisible = true;

  }
  // 确认提交审核
  public async handlesubAuditOk() {

    // 表单信息推送
    const parmas = {
      // 项目id
      projectId: this.project.id,
      // 编号
      code: this.status.pro.code,
      // 项目名称
      name: this.status.pro.name,
      // 项目区域ID
      areaId: this.status.pro.aera.value,
      // 项目区域类型
      areaName: this.status.pro.aera.label,
      // 项目类型
      type: this.status.pro.type.value,
      // 项目阶段
      stage: this.status.pro.step.value,
      // 项目进度
      rate: this.status.pro.progress.value,
      // 描述
      desc: this.status.pro.info,
      // 场景名称
      modelGroupName: this.status.pro.modelName,
      // 文件类型
      fileType: this.status.pro.fileType.value,
      // 模型类型
      modelType: this.status.pro.modelType.value,
      // 模型进度类型（基础/进度）
      modelSecondType: this.status.pro.modelprogress.value,
      modelGroupId: this.modelGroupId,
      // 模型数据 (2019.6.18 修改为业务端数据查询)
      // syncModelInfo: {
      //   modelGroupId: this.modelGroupId,
      //   fileList: this.anaJsonArr,
      //   ip: 'gg03p.prd.zzj',
      //   port: '2025',
      // }
    };
    const res = await this.modelListService.SysncData(parmas);
    if (res.success) {
      this.message.success('提交成功')
      this.currentModelGroup.jwStatus = 1; // 更改场景状态为审核中
      this.isbtn = false; // 隐藏提审按钮
      // this.isaudit = false; //隐藏上传按钮
      // 更新状态为审核中
      this.modelLists.forEach(modelitem => {
        if (modelitem.jwStatus === 0) {
          modelitem.jwStatus = 1; // 审核中
        }
      });
    } else {
      this.message.warning(res.error);
    }
    //this.init()
    this.subAuditVisible = false;
  }


  // 关闭建委审核弹窗
  public subAuditCancel() {
    this.subAuditVisible = false;
  }

  // 查询审核结果
  public async resAudit(item) {
    // console
    this.isShowModelResList = true;
    // 获取审核结果
    let parmas = {
      'modelGroupId': this.modelGroupId,
      'maxResultCount': 1000,
      'skipCount': 0,
      'modelId': item.id
    }
    const res = await this.modelListService.getAuditLists(parmas);
    console.log(res)
    if (res.success) {
      this.modelResLists = res.result.items;
    }

  }
  // 关闭审核结果列表弹窗
  public closeAuditResCancel() {
    this.isShowModelResList = false;
  }

  // 下拉列表选择事件
  public selChange(e) {
    console.log(e)

  }
  public reload() {
    this.uploadModel.nativeElement.click();
  }
  // 替换模型(2019.6.18)
  public async swapModel(item) {
    this.modalService.info({
      nzTitle: '确认替换《' + item.fileName + '》?',
      nzContent: '<b style="color: red;">点击确定选择新模型，原模型文件将会被删除，请谨慎操作。</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {

        // 重新执行上传动作
        // debugger;
        this.uploadModel.nativeElement.click();
        this.fileLoadStatus.subscribe(res => {
          console.log(res)
          // 如果重新上传成功才执行删除操作
          if (res) {
            this.replace(item, res)
          }
        })

      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }

  // 替换接口调用
  public async replace(item, fileInfo) {
    // // 业务后台图形删除
    let delRes = await this.modelListService.deleteModel({ input: item.id });
    if (!delRes.success) {
      return;
    }
    // 图形后台图形删除
    let Params = {
      hash: item.hash,
      modelGroupId: item.modelGroupId,
      modelName: item.fileName
    }
    const serDelRes = await this.modelListService.delModelFromGraphicsServer(Params);
    // 调用业务后台替换接口

    const params = {
      modelGroupId: item.modelGroupId,
      projectId: item.projectId,
      projectModelId: item.id
    };
    const resForReSyncData = await this.modelListService.reSyncData(params);
    console.log("resForReSyncData",resForReSyncData)
    // 结果判断
    if (resForReSyncData.success) {
      this.message.success('替换成功')
      this.modelLists.forEach((element, idx) => {
        console.log("element",element);
        if (element.id === item.id) {
          this.modelLists.splice(idx, 1);
        }
        if (element.id === this.delFileId) {
          element.jwStatus = 1;
        }
      });
    } else {
      this.message.warning(resForReSyncData.error.message);
    }
    let pramas = {
      modelGroupId: item.id,
      maxResultCount: 1000,
      projectId: item.projectId
    }
    const res = await this.modelListService.getModelLists(pramas);
    if (res.success) {
      // console.log(res)
      this.modelLists = res.result.items;
    } else {
      this.message.warning(res.error.message);
    }
  }

  /**
   * 路由
   * @param item 当前点击场景
   */
  public async routerTo(item) {
    console.log(item)
    const json = {
      modelGroupId: item.id,
      taskId: item.taskId
    }
    if (item.taskId == '00000000-0000-0000-0000-000000000000') {
      this.message.create('warning', '暂无可用模型');
      return
    }
    // 查询解析进度
    const result = await this.modelListService.transformation(json);
    if (!result.item.taskState.done && !result.item.taskState.found && !result.item.taskState.successed) {
      this.message.create('warning', '模型转换失败，请联系管理员');
      return;
    }
    if (!result.item.taskState.done && result.item.taskState.found) {
      this.message.loading('模型转换中，请耐心等待');
      return;
    }
    result.item.modelList.forEach(el => {
      if (el.percent == 0 && el.errorMessage != 'FileAlreadyParsed') {
        this.message.create('warning', `模型  ` + '【' + el.modelName + '】' + '转换失败');
      }

    });
    this.toModel(item);
  }
  // 跳转当前场景 并缓存
  public toModel(item) {
    window.localStorage.setItem('model', JSON.stringify(item));
    this.routeInfo.queryParams.subscribe(queryParams => {
      const projectId = JSON.parse(window.localStorage.getItem('project')).id;
      Utils.openPath(`/inner/project/${projectId}/model?info=project&id=init`)
      // window.location.href = `/inner/project/${projectId}/model?info=project&id=init`
      // this.router.navigate([`inner/project/${projectId}/model`], { queryParams });
    });
  }

  ngOnInit() {
    this.init();
  }

}
